<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="15">
				<div class="layout-padding-auto layout-padding-view">
					<el-scrollbar>
						<el-tree
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="relative layout-padding-auto layout-padding-view">
					<!-- 地图节点 -->
					<div class="w-full h-full" ref="amapRef" id="map"></div>
					<!-- 图层 -->
					<div class="controls">
						<el-button type="primary" size="small" @click="handelLayerControl">图层</el-button>
						<el-collapse-transition>
							<div v-show="layerControl" class="py-2">
								<div class="flex flex-col w-[26px]">
									<el-tooltip placement="right" content="放大">
										<el-button icon="Plus" type="info" size="small" @click="handleZoom(true)" />
									</el-tooltip>
									<el-tooltip placement="right" content="缩小">
										<el-button class="mt-1 !ml-0" icon="Minus" type="info" size="small" @click="handleZoom(false)" />
									</el-tooltip>
									<el-tooltip placement="right" content="风场" :width="60" effect="light">
										<template #content>
											<div class="w-[60px]">
												<el-radio-group v-model="mapType" @change="handleMapType">
													<el-radio :label="10" size="small">矢量</el-radio>
													<el-radio :label="20" size="small">卫星</el-radio>
												</el-radio-group>
											</div>
										</template>
										<el-button class="mt-3 !ml-0" icon="CopyDocument" type="info" size="small" />
									</el-tooltip>
									<el-tooltip placement="right" content="风场">
										<el-button class="mt-1 !ml-0" icon="WindPower" type="info" size="small" @click="handleWind(windState ? false : true)" />
									</el-tooltip>
									<el-tooltip placement="right" content="显示名称">
										<el-button class="mt-1 !ml-0" icon="PriceTag" type="info" size="small" @click="toggleName" />
									</el-tooltip>
								</div>
							</div>
						</el-collapse-transition>
					</div>
					<!-- 污染等级 -->
					<div class="absolute z-[1000] bottom-[10px] right-[10px]">
						<div class="flex leading-[20px] text-xs">
							<div class="w-[5em] text-center" v-for="item in level" :style="{ 'background-color': item.color }" :key="item.label">
								{{ item.label }}
							</div>
						</div>
					</div>
					<!-- 监测点类型,指标类别 -->
					<div class="site">
						<div class="flex flex-col items-center justify-center">
							<div>
								<el-radio-group v-model="m_CurrentTypeIndicator" size="small" @change="toggleTypeLayerAll" class="!flex-nowrap">
									<el-radio-button :label="-1">全部</el-radio-button>
									<el-radio-button :label="0">微型网格点</el-radio-button>
									<el-radio-button :label="1">微型VOC站</el-radio-button>
								</el-radio-group>
							</div>
							<div>
								<el-radio-group v-model="m_CurrentFactorIndicator" size="small" @change="toggleFactorLayerAll" class="!flex-nowrap">
									<el-radio-button
										v-for="item in m_CurrentTypeIndicator_list"
										:key="item.name"
										:label="item.name"
										v-show="item.label === 'VOC' ? m_CurrentTypeIndicator === 1 : true"
									>
										{{ item.label }}
									</el-radio-button>
								</el-radio-group>
							</div>
						</div>
					</div>
					<!-- 数据统计 -->
					<div class="absolute z-[1000] bottom-[26px] left-3 bg-[#fff] text-xs">
						<div class="flex flex-col justify-center rounded-[4px] overflow-hidden shadow">
							<div
								class="px-2 flex items-center justify-center leading-[26px] cursor-pointer text-xs"
								:style="{ color: airLevel === '全部' ? '#fff' : '#2e5cf6', 'background-color': airLevel === '全部' ? '#2e5cf6' : '#fff' }"
								@click="handleAirLevel('全部')"
							>
								<div>全部</div>
								<div class="pl-2">{{ levelStatistic.countAll }}</div>
							</div>
							<div
								v-for="item in levelStatistic.list"
								:key="item.label"
								class="px-2 flex items-center justify-center cursor-pointer border-t-[#dcdfe6] border-t-[1px] leading-[30px] text-xs"
								:style="{ color: airLevel === item.label ? '#000' : item.color, 'background-color': airLevel === item.label ? item.color : '#fff' }"
								@click="handleAirLevel(item.label)"
							>
								<div>{{ item.label }}</div>
								<div class="pl-2">{{ item.count }}</div>
							</div>
						</div>
					</div>
				</div>
			</pane>
		</splitpanes>
		<el-drawer v-model="drawer" title="站点数据" modal-class="modalClass" :destroy-on-close="true" :size="500" @closed="handleClosed">
			<MapDrawer :data="pageData" />
		</el-drawer>
	</div>
</template>

<script setup lang="ts" name="systemAirRealTimeData">
import { fetchList } from '/@/api/platform/airRealTimeData';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { handleTree } from '/@/utils/other';
import * as L from 'leaflet';
import 'leaflet-velocity/dist/leaflet-velocity';
import windJSON from '/@/assets/wind.json';
import { m_CurrentTypeIndicator_list, level, getAQILimit } from './data';
import waveGif from '/@/assets/images/wave.gif';
import MapDrawer from './components/mapDrawer.vue';
const siteId = ref('');
const drawer = ref(false);
let m_map: any;
let m_satelliteLayer: any;
let m_vectorLayer: any = null;
let m_velocityLayer: any = null;
let timer: any;
let m_markerLayer: any = null;
let m_gifMarker: any;
const amapRef = ref();
const areaInfo = ref({});
const layerControl = ref(false);
const windState = ref(false);
const mapType = ref(10);
const showTags = ref(true);

const m_CurrentTypeIndicator = ref(-1);
const airLevel = ref('全部');
const m_CurrentFactorIndicator = ref(m_CurrentTypeIndicator_list[0].name);
const pageData: any = ref([]);
const levelStatistic = reactive({
	list: level,
	countAll: 0,
});
// 区域树使用的数据
const treeData = reactive({
	list: [],
	defaultProps: {
		label: 'name',
	},
});

async function initMap() {
	m_satelliteLayer = L.tileLayer('https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', { subdomains: '1234' });
	m_vectorLayer = L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
		subdomains: '1234',
	});
	m_map = L.map('map', {
		resizeEnable: true,
		zoom: 15,
		minZoom: 3,
		maxZoom: 18,
		// center: [pageData.value[0]?.latitude, pageData?.value[0]?.longitude],
		center: [31.51514, 104.604208],
		preferCanvas: true,
		zoomControl: false,
	});
	m_vectorLayer.addTo(m_map);
	m_map.on('click', function () {
		if (m_gifMarker != undefined) {
			m_gifMarker.removeFrom(m_map);
		}
	});
	m_markerLayer = L.layerGroup();
	m_map.addLayer(m_markerLayer);
	initVelocityLayer();
}
// 风场
const initVelocityLayer = () => {
	m_velocityLayer = L.velocityLayer({
		displayValues: true,
		displayOptions: {
			velocityType: 'Global Wind',
			displayPosition: 'bottomleft',
			displayEmptyString: 'No wind data',
		},
		data: windJSON,
		minVelocity: 0, // used to align color scale
		maxVelocity: 15, // used to align color scale
		velocityScale: 0.01, // modifier for particle animations, arbitrarily defaults to 0.005
		colorScale: ['#808080'], //风场颜色
		onAdd: null,
		onRemove: null,
	});
};
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	areaInfo.value = e;
	getDataList();
};

const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDataList();
		}
	});
};
const getDataList = () => {
	fetchList({ siteId: unref(siteId) }).then((res) => {
		pageData.value = res.data;
		if (!m_map) {
			initMap();
		}
		initCount();
		// initMarkerLayer();
	});
};
// 定时刷新
const handleSwitch = (val: boolean) => {
	if (val) {
		timer = setInterval(() => {
			getDataList();
		}, 30 * 1000);
	} else {
		clearInterval(timer);
	}
};
onMounted(() => {
	getTreeDate();
});
onUnmounted(() => {
	handleSwitch(false);
});

const handelLayerControl = () => {
	layerControl.value = !layerControl.value;
};
// 缩放
const handleZoom = (zoom: boolean) => {
	if (zoom) {
		m_map.zoomIn();
	} else {
		m_map.zoomOut();
	}
};
// 风场
const handleWind = (s: boolean) => {
	windState.value = !windState.value;
	if (s) {
		m_velocityLayer.addTo(m_map);
	} else {
		m_velocityLayer.removeFrom(m_map);
	}
};
// 地图切换
const handleMapType = (v: number) => {
	if (v == 10) {
		m_satelliteLayer.removeFrom(m_map);
		m_vectorLayer.addTo(m_map);
	} else {
		m_vectorLayer.removeFrom(m_map);
		m_satelliteLayer.addTo(m_map);
	}
};
// 污染统计切换
const handleAirLevel = (l: string) => {
	airLevel.value = l;
};
const initCount = () => {
	if (pageData.value.length) {
		const list = pageData.value.filter((item: any) => {
			if (m_CurrentTypeIndicator.value == -1 || item.monitorType == m_CurrentTypeIndicator.value) {
				return true;
			} else {
				return false;
			}
		});
		levelStatistic.countAll = list.length;
		levelStatistic.list.forEach((item, index: number) => {
			item.count = list.filter((d: any) => {
				return d.status > 0 && getAQILimit(m_CurrentFactorIndicator.value, d[m_CurrentFactorIndicator.value.toLowerCase()]) === index;
			}).length;
		});
		initMarkerLayer();
	}
};
const toggleTypeLayerAll = () => {
	initCount();
};
const toggleFactorLayerAll = () => {
	initCount();
};
const initMarkerLayer = () => {
	m_markerLayer && m_markerLayer.clearLayers();
	const m_stationList = pageData.value.filter((item: any) => {
		if (m_CurrentTypeIndicator.value == -1 || item.monitorType == m_CurrentTypeIndicator.value) {
			return true;
		} else {
			return false;
		}
	});
	const makers: any = [];
	m_stationList.forEach((item: any, index) => {
		let aqilevel = getAQILimit(m_CurrentFactorIndicator.value, item[m_CurrentFactorIndicator.value.toLowerCase()]);

		let icon = L.icon({
			iconUrl: level[aqilevel].siteIcon,
			iconSize: [40, 40],
			iconAnchor: [20, 40],
			popupAnchor: [0, -40],
			tooltipAnchor: [0, -44],
		});
		let marker = L.marker([item?.latitude, item?.longitude], { icon: icon });
		makers.push(marker);
		marker.extra = item;
		marker.setZIndexOffset(1);
		let icon_0 = L.icon({
			iconUrl: waveGif,
			iconSize: [64, 64],
			iconAnchor: [32, 32],
		});
		marker.sub = L.marker([item?.latitude, item?.longitude], { icon: icon_0 });
		marker.sub.setZIndexOffset(0);
		if (item.status <= 0) {
			marker.bindTooltip(item.siteName + ' ' + item[m_CurrentFactorIndicator.value.toLowerCase()], {
				direction: 'top',
				permanent: true,
			});
		} else {
			marker.bindTooltip(item.siteName + ' ' + item[m_CurrentFactorIndicator.value.toLowerCase()], {
				direction: 'top',
				permanent: true,
			});
		}
		marker.on('click', (e: any) => {
			m_gifMarker && m_gifMarker.removeFrom(m_map);
			m_gifMarker = e.target.sub;
			m_gifMarker.addTo(m_map);
			drawer.value = true;
		});
		m_markerLayer.addLayer(marker);
		// }
	});
	nextTick(() => {
		// 标记点自适应缩放
		if (makers.length) {
			var group = L.featureGroup(makers); //add markers array to featureGroup
			m_map.fitBounds(group.getBounds());
		}
	});
};
// 显示名称
const toggleName = () => {
	for (const i in m_markerLayer._layers) {
		const marker = m_markerLayer._layers[i];
		if (showTags.value) {
			marker.closeTooltip();
		} else {
			marker.openTooltip();
		}
	}
	showTags.value = !showTags.value;
};
const handleClosed = () => {
	m_gifMarker && m_gifMarker.removeFrom(m_map);
};
</script>

<style lang="scss" scoped>
:deep(.amap-marker-label) {
	color: #000;
	background: #00e400;
	border: unset;
	border-radius: 4px;
}
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
:deep(.modalClass) {
	background-color: unset;
}
:deep(.el-drawer__header) {
	margin-bottom: 0;
}

.controls {
	position: absolute;
	top: 15px;
	left: 15px;
	z-index: 1000;
}

.site {
	position: absolute;
	top: 10px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 1000;
}
</style>
